/* Class Action
 * 
 * Functionality for calling a server side action
 * 
 * @author David Lindkvist (david.lindkvist@shapeshift.se)
 */

PWF.Action = Class.create(PWF.mixin.AjaxRequest,
{
	/**
	 * @constructor
	 * @param {String} actionUrl URL to the server action
	 * @param {function} callbackInit Function to call when the action is executed
	 * @param {function} callbackSuccess Function to call if action is successful
	 * @param {function} callbackFailure Function to call if action fails
	 * @param {String} method [optional] Http method to use for the Ajax request. Default is 'post'. 
	 */
	initialize: function(actionUrl, 
						 callbackInit, 
						 callbackSuccess, 
						 callbackFailure, 
						 method) 
	{
		this.actionUrl = actionUrl;
		this.callbackInit = callbackInit;
		this.callbackSuccess = callbackSuccess;
		this.callbackFailure = callbackFailure;
		this.method = method;
	},

	run: function() 
	{	
		//call custom init method with runningInstance
		this.callbackInit();

		//call action
		this.callAction(this.actionUrl, this.method);
	},

	onRequestSuccess: function(/*Object*/transport) 
	{	
		//parse json
		var json = transport.responseText.evalJSON();

		//check action outcome for success/failure
		if(json.outcome == 1)
		{
			Log.debug('action outcome: success');
			this.callbackSuccess(json);
		}
		else if(json.outcome == -1)
		{
			Log.debug('action outcome: failed ('+json.errorMsg+')');
			this.callbackFailure(json.errorMsg, json)
		}
		//not logged in (session timeout)
		else if(json.outcome == -2)
		{
			Log.debug('action outcome: invalid session');
			this.callbackFailure('Kunde inte utföra åtgärden - ej inloggad');

			//request login and re-run action
			if(!PWF.loginHandlerInProgress)
			{
				Log.debug('action login required - calling PWF.loginHandler()');
				PWF.loginHandlerInProgress = true;
				PWF.loginHandler(this.loginHandlerSuccess.bind(this));
			}
		}		
	},
	
	loginHandlerSuccess: function()
	{
		Log.debug('action login success - re-running action');
	
		PWF.loginHandlerInProgress = false;
		
		//re-run action
		this.run();
	},
	
	onRequestFailure: function(/*Object*/request) 
	{
		Log.error('action failure: '+request.status);
		this.callbackFailure('Ett fel har uppstått, var god försök igen (e)');
	},

	onRequestException: function(/*Object*/request, ex) 
	{
		Log.error('action exception: '+request.status+', '+ex);
		this.callbackFailure('Ett fel har uppstått, var god försök igen (x)');
	}
});
